/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2024-11-04 09:52:39
 * @LastEditTime: 2024-11-13 23:16:51
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 工具包
 * @FilePath: \markdown-magic\src\utils\index.js
 * @Copyright 版权声明
 */

// 转base64编码
export const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let fileResult = "";
    reader.readAsDataURL(file); //开始转
    reader.onload = function () {
      fileResult = reader.result;
    };
    //转失败
    reader.onerror = function (error) {
      reject(error);
    };
    //转结束 resolve 出去
    reader.onloadend = function () {
      resolve(fileResult);
    };
  })
}

// 下载pdf文件
export const downloadPdf = (pdfBytes, filename) => {
  const blob = new Blob([pdfBytes], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.click();
  URL.revokeObjectURL(url);
}

// 下载word文件
export const downloadWord = (wordBytes, filename) => {
  const blob = new Blob([wordBytes], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.click();
  URL.revokeObjectURL(url);
}

// 文本转ArrayBuffer
export function textToArrayBuffer(text) {
  const encoder = new TextEncoder();
  const uint8Array = encoder.encode(text);
  return uint8Array.buffer;
}

// ArrayBuffer转文本
export function arrayBufferToText(buffer) {
  const decoder = new TextDecoder();
  return decoder.decode(buffer);
}